package kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;

public class kafkaTuisong {
        public static void main(String[] args) throws InterruptedException, IOException {
            // Kafka配置
            Properties props = new Properties();
            props.put("bootstrap.servers", "niit01:9092");
            props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
            props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

            // 创建KafkaProducer
            KafkaProducer<String, String> producer = new KafkaProducer<>(props);

            try (BufferedReader reader = new BufferedReader(new FileReader("C:\\pro1.txt"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 生成随机数据并发送到stuInfo主题
                    String randomData = generateRandomData(line);
                    producer.send(new ProducerRecord<String,String>("stuInfo", randomData));
                    System.out.println(randomData);
                    // 休眠5秒
                    Thread.sleep(5000);
                    //Thread.sleep((long)(Math.random()*450 + 50));
                }
            } finally {
                // 关闭Producer
                producer.close();
            }
        }

        // 生成随机数据的方法
        private static String generateRandomData(String originalData) {
            Random random = new Random();
            // 生成随机数据
            String[] fields = originalData.split("\t");

            String classNumber = fields[0];
            String name = fields[1];
            String birthday = fields[2];
            String studentNumber = fields[3];
            String semester = fields[4];
            String enrollmentStatus = fields[5];
            String gender = fields[6];

            // 拼接数据并用制表符分隔
            return classNumber + "\t" + name + "\t" + gender + "\t" + birthday + "\t" + studentNumber + "\t" + semester + "\t" + enrollmentStatus;


        }
    }


